<template>
  <div class="comment-container">
    <a-comment>
      <template #avatar>
        <a-avatar :src="currentAvatar" :alt="currentAuthor" />
      </template>
      <template #content>
        <a-form-item>
          <a-textarea v-model:value="value" :rows="1" />
        </a-form-item>
        <a-form-item>
          <a-button
            html-type="submit"
            :loading="submitting"
            type="primary"
            @click="handleSubmit"
          >
            评论
          </a-button>
        </a-form-item>
      </template>
    </a-comment>
    <a-list
      v-if="comments.length"
      :data-source="comments"
      :header="`${comments.length} ${
        comments.length > 1 ? '条评论' : '条评论'
      }`"
      item-layout="horizontal"
    >
      <template #renderItem="{ item }">
        <a-list-item>
          <a-comment
            :author="item.author"
            :avatar="item.avatar"
            :content="item.content"
            :datetime="item.datetime"
          />
        </a-list-item>
      </template>
    </a-list>
  </div>
</template>
<script lang="ts" setup>
import { createComment, deleteComment, getCommentList } from "@/api/comment";
import { defineProps, onMounted, ref, watch, defineEmits } from "vue";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
dayjs.extend(relativeTime);
import { getMinioUrl } from "@/utils/minio";
import { useLoginUserStore } from "@/store/useLoginUserStore";

const formatTime = (timeStr: string): string => {
  return dayjs(timeStr).format("YYYY-MM-DD HH:mm");
};

const currentAuthor = ref<string>("");
const currentAvatar = ref<string>("");
const props = defineProps<{
  blogId: number;
}>();

const submitting = ref<boolean>(false);
const value = ref<string>("");

interface Comment {
  content: string;
  author: string;
  avatar: string;
  datetime: string;
}
const comments = ref<Comment[]>([]);
const userStore = useLoginUserStore();

type Emits = {
  update: [visible: boolean];
  submit: [data: string];
  "comment-updated": [count: number];
};
const emit = defineEmits<Emits>();

watch(
  () => userStore.loginUser,
  (newUser) => {
    if (newUser) {
      currentAuthor.value = newUser.username || "";
      currentAvatar.value = getMinioUrl(newUser.avatar || "");
    }
  },
  { deep: true, immediate: true }
);

const handleSubmit = async () => {
  if (!value.value) {
    return;
  }

  submitting.value = true;

  try {
    console.log("提交评论：", value.value);
    console.log("当前博客ID：", props.blogId);
    await createComment({
      blogId: props.blogId,
      content: value.value,
    });

    await fetchComments();

    emit("comment-updated", comments.value.length);

    value.value = "";
  } catch (error) {
    console.error("提交失败:", error);
  } finally {
    submitting.value = false;
  }
};

const fetchComments = async () => {
  try {
    const res = await getCommentList(props.blogId);
    console.log("评论详情：", res.data);
    comments.value = res.data.map((item) => ({
      author: item.username,
      avatar: getMinioUrl(item.avatar),
      content: item.content,
      datetime: formatTime(item.createdAt),
    })) as Comment[];
  } catch (error) {
    console.error("获取评论失败:", error);
  }
};

onMounted(async () => {
  await userStore.fetchLoginUser();
  currentAuthor.value = userStore.loginUser?.username || "";
  currentAvatar.value = getMinioUrl(userStore.loginUser?.avatar || "");
  await fetchComments();
});
</script>

<style scoped></style>
